package com.example.watermark.service.impl;

import com.example.watermark.service.IMarkService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: Yenn
 * @Description: 水印抽象类
 */
public abstract class AbstractMarkService implements IMarkService {
    @Override
    public String watermark(MultipartFile image, String uploadPath, String realUploadPath) {
        String logoFileName = "logo_"+image.getOriginalFilename();
        OutputStream os = null;

        try {
            Image image2 = ImageIO.read(image.getInputStream());
            int width = image2.getWidth(null);
            int height = image2.getHeight(null);

//            1、创建缓存图片对象
            BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

//            2、        创建JAVA绘图工具对象
            Graphics2D graphics2D = bufferedImage.createGraphics();

//            3、使用绘图工具对象，将原图绘制到缓存图片对象
            graphics2D.drawImage(image2,0,0,width,height,null);

            //  4、使用绘图工具，将水印（文字/图片）绘制到缓存图片对象
            draw(width, height,bufferedImage, graphics2D);


//            5、        创建图像编码工具类
            String des = realUploadPath+ File.separator+ logoFileName;
            os = new FileOutputStream(des);

            JPEGImageEncoder jpegImageEncoder = JPEGCodec.createJPEGEncoder(os);

//            6、使用图片编码工具类，输出缓存图像到模板图片文件
            jpegImageEncoder.encode(bufferedImage);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return uploadPath+File.separator+logoFileName;
    }

    /**
     * 绘制水印
     * @param width
     * @param height
     * @param bufferedImage
     * @param graphics2D
     * @throws IOException
     */
    abstract void draw(int width, int height, BufferedImage bufferedImage, Graphics2D graphics2D) throws IOException;


    public int getTextLength(String text){
        int length = text.length();

        for(int i=0;i<text.length();i++){
            String s = String.valueOf(text.charAt(i));
            if(s.getBytes().length>1){
                length++;
            }
        }

        length = length%2==0?length/2:length/2+1;
        return length;
    }

}
